<?php

namespace App\Models\Arts;

use App\Master\Framework\Extend\DataUtil;
use App\Models\BaseModel;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class WebMenusModel extends BaseModel
{
    use HasFactory;

    protected $table      = 'web_menus';
    public    $timestamps = false;

    /**
     * 默认查询字段
     *
     * @var array|string[]
     */
    public array $select = ['*'];

    /**
     * 获取导航
     * @param string $path
     * @return array
     */
    public static function getMenusParentsRecursion(string $path = ''): array
    {
        $menus = self::query()
            ->select(['id','parent_id','parent_ids','level','type','name','link','pinyin','show_child','module_page'])
            ->whereIn('level',[1,2])
            ->where('status',1)
            ->where('is_delete',0)
            ->orderBy('sort', 'desc')
            ->get()
            ->toArray();
        if (!$menus){
            return [];
        }

        $menuOpera = $menus;

        foreach ($menus as $key=>$val){
            $menus[$key]['active'] = 0;
            $tail = $val['pinyin'] == 1 ? "/{$val['id']}" : '';
            $link = "/{$val['link']}$tail";

            if ($link == "/{$path}") {
                $menus[$key]['active'] = 1;
            }

            // 如果当前菜单是 二级 则也要设置顶级菜单 高亮
            if ($val['level'] == 2 && $menus[$key]['active'] == 1){
                $parentKey = self::getMenusKey($val['parent_id'],$menuOpera);
                if ($parentKey >= 0){
                    $menus[$parentKey]['active'] = 1;
                }
            }

            // 初始化link
            $menus[$key]['link'] = $link;
            if ($val['show_child'] == 1){
                $child = self::getChildOnce($val['id'],$menuOpera);
                if (!empty($child['link'])){
                    $tail = $child['pinyin'] == 1 ? '/'.$child['id'] : '';
                    $menus[$key]['link'] = "/{$child['link']}$tail";
                }
            }
        }

        return DataUtil::recursion ($menus, 'id', 'parent_id');
    }

    public static function getMenusKey(int $parent_id,array $menus)
    {
        $keys = '';
        foreach ($menus as $key=>$val){
            if ($val['id'] == $parent_id){
                $keys = $key;
                break;
            }
        }
        return $keys;
    }

    public static function getChildOnce(int $parent_id,array $menus)
    {
        $parent = -1;
        foreach ($menus as $val){
            if ($val['parent_id'] == $parent_id){
                $parent = $val;
                break;
            }
        }
        return $parent;
    }
}
